<template>
  <div class="list">
    <h3 v-if="isFirst">Welcome</h3>
    <h3 v-if="info.isLoading">Loading...</h3>
    <h3 v-if="info.errMsg">{{ info.errMsg }}</h3>
    <h3 v-if="isNoUser">Sorry, no user...</h3>
    <ul v-if="info.users.length">
      <li v-for="user in info.users" :key="user.id">
        <a :href="user.html_url" target="_blank">
          <img :src="user.avatar_url" alt="avatar">
        </a>
        <p>{{ user.login }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'SearchList',
  data() {
    return {
      isFirst: true,
      info: {
        isLoading: false,
        errMsg: '',
        users: [],
      },
      isNoUser: false
    }
  },
  methods: {
    dontWelcome() {
      this.isFirst = false
      this.$bus.$off('dontWelcome')
    },
    updateUserList(usersObj) {
      // 合并对象数据，后替换前
      this.info = { ...this.info, ...usersObj }
      if (this.info.users.length === 0 && !this.info.isLoading) {
        this.isNoUser = true
      } else {
        this.isNoUser = false
      }
    },
  },
  beforeMount() {
    this.$bus.$on('updateUserList', this.updateUserList)
    this.$bus.$on('dontWelcome', this.dontWelcome)
  },
  beforeDestroy() {
    this.$bus.$off('gupdateUserList')
  },
}
</script>

<style lang="less">
.list ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
}

.list ul li {
  float: left;
  width: 33%;
  height: 130px;
  border: 1px solid #ccc;
  text-align: center;
}

.list ul img {
  height: 100px;
}
</style>
